using System.Threading.Tasks.Dataflow;
using System;
using Microsoft.AspNetCore.Mvc;
using Daemon.Model;
using Microsoft.AspNetCore.Http;
using Daemon.Common;
using Daemon.Common.Filter;
using System.IO;
using System.Text;
using Daemon.Repository.Contract;
using System.Linq;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Net;
namespace DaemonAPI
{
    [ApiController]
    [Route("daemonApi/[controller]/[action]")]
    public class UploadController : ControllerBase
    {

        private readonly IClientConfigRepository _clientConfigRepository;

        private readonly IAdminFileRepository _adminFileRepository;

        private readonly IConfiguration _configuration;

        public UploadController(IClientConfigRepository clientConfigRepository, IAdminFileRepository adminFileRepository, IConfiguration configuration)
        {
            _clientConfigRepository = clientConfigRepository;
            _adminFileRepository = adminFileRepository;
            _configuration = configuration;
        }

        [HttpPost]
        [Route("")]
        [DisableRequestSizeLimit]
        public ActionResult Upload([FromForm] IFormFileCollection file, [FromQuery] int? treeId)
        {
            var path = GetFileAddress()?.FileAddress;
            var userId = _adminFileRepository.GetUserId();
            Console.Write("" + userId);
            List<AdminFile> addFiles = new List<AdminFile>();
            for (var i = 0; i < file.Count; i++)
            {
                AdminFile blogFile = new AdminFile() { IsDelete = 0, AddTime = DateTime.Now };
                var currentFile = file[i];
                var contentType = currentFile.ContentType;
                var filenameMine = currentFile.FileName.Split('\\');
                blogFile.Name = currentFile.FileName;
                string[] fileNameArray = filenameMine[filenameMine.Length - 1].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                blogFile.Ext = fileNameArray[fileNameArray.Length - 1];
                var dirName = $"{DateTime.Now.ToString("yyyyMMdd")}/{fileNameArray[fileNameArray.Length - 1]}";
                var currentFilePath = $"{path}/{dirName}";
                DirFile.CreateDir($"{currentFilePath}");
                string finalPath = Path.Combine(currentFilePath, currentFile.FileName);
                blogFile.FilePath = finalPath;
                var bytes = GetByte(currentFile);
                SaveFileToDir(finalPath, bytes);
                var serverFilePath = $"http://{_configuration.GetSection("AppSettings:ip")?.Value}:{_configuration.GetSection("AppSettings:port")?.Value}/Daemon/{dirName}/{currentFile.FileName}";
                blogFile.ServerFilePath = serverFilePath;
                blogFile.AddUserId = 1;
                blogFile.FileSizeKB = (decimal)bytes.Length / 1024;
                blogFile.UpdateUserId = 1;
                if (treeId.HasValue)
                {
                    blogFile.TreeId = treeId.Value;
                }
                addFiles.Add(blogFile);
            }
            return new ResultModel(HttpStatusCode.OK, "上传成功！", SaveFile(addFiles));
        }

        private List<AdminFile> SaveFile(List<AdminFile> files)
        {
            var addFiles = _adminFileRepository.AddRangeWithRelationships(files);
            return addFiles.ToList();
        }

        private void SaveFileToDir(string filePath, byte[] buffer)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                fs.Write(buffer, 0, buffer.Length);
                //文件大小
                // string fileMax = System.Math.Ceiling(fs.Length / 1024.0) + "kb";
            }
        }

        /// <summary>
        /// 获取保存文件的磁盘路径
        /// </summary>
        /// <returns></returns>
        private ClientConfig GetFileAddress()
        {
            var sysInfo = _clientConfigRepository.FindAll().FirstOrDefault();
            return sysInfo;
        }

        protected byte[] GetByte(IFormFile file)
        {
            byte[] bytes = new byte[file.Length];

            using (var stream = file.OpenReadStream())
            {
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    reader.BaseStream.Read(bytes, 0, bytes.Length);
                    reader.BaseStream.Seek(0, SeekOrigin.Begin);
                }
            }
            return bytes;
        }
    }
}
